package com.dream.utils.email;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;

import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dream.utils.log.DreamLogUtils;
import com.dream.utils.system.cfg.SystemConfigUtils;

/**
 * @copyright evan
 * @author evan
 * @Revision
 * @date 2012/09/01
 */
@Service("MailCenterService")
public class MailCenterServiceImpl implements MailCenterService {

	@Resource(name="javaMailSender")
	private JavaMailSender javaMailSender;

	@Transactional
	public MailSendingResult sendMail(EMailBean mail,MailServerType type) {

		try {
			if (javaMailSender instanceof JavaMailSenderImpl) {
				
				String user = SystemConfigUtils.instance().getValue("mail."+type+".user");
				String pwd = SystemConfigUtils.instance().getValue("mail."+type+".password");
				JavaMailSenderImpl mailSenderImpl = (JavaMailSenderImpl) javaMailSender;
				mailSenderImpl.setHost(SystemConfigUtils.instance().getValue("mail."+type+".host"));
				mailSenderImpl.setUsername(user);
				mailSenderImpl.setPassword(pwd);
				mailSenderImpl.setJavaMailProperties(SystemConfigUtils.instance().getProperties("mail."+type+".properties"));
				mail.setFromEmail(user);
				
			}

			MimeMessagePreparator mimeMessagePreparator = prepare(mail);
			javaMailSender.send(mimeMessagePreparator);
			return MailSendingResult.SUCCESS;

		} catch (Exception ex) {
			DreamLogUtils.error(this,"static","init mail exception",ex);
			return MailSendingResult.FAIL;
		}

	}

	private MimeMessagePreparator prepare(final EMailBean mail) {
		MimeMessagePreparator message = new MimeMessagePreparator() {
			public void prepare(final MimeMessage mimeMessage) throws Exception {
				MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
				
				helper.setFrom(mail.getFromEmail());
				helper.setTo(mail.getToEmail());
				helper.setText(mail.getContent() ,Boolean.TRUE);
				helper.setSubject(mail.getSubject());
				
			}
		};
		return message;
	}
}
